<?php
Raise::load('core.io.RaiseStream');

/**
 * RaiseConsoleStream class
 * provides console IO functionality
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core.io
 * @since 1.2
 */
class RaiseConsoleStream extends RaiseStream {

    public function close() {

    }

    public function isReadable() {
        return true;
    }

    public function isSeekable() {
        return false;
    }

    public function isWriteable() {
        return true;
    }

    public function length() {
        throw new RaiseInvalidRequestException('Length is not available in RaiseConsoleStream');
    }

    /**
     * Read in data from the user's input.
     * @param int $length Ignored.
     * @return string The data from user's input
     */
    public function read($length) {
        static $buffer = '';

        $fp = fopen('php://stdin', 'r');
        $line = $buffer;
        while($l = fgets($fp, 1024)){
            $l = RaiseText::neutralizeNewlines($l);
            $line .=  $l;
            $newLinePos = strpos($line, RaiseText::NEWLINE_NIX);
            if($newLinePos !== false){
                break;
            }
        }
        fclose($fp);
        $newLinePos = strpos($line, RaiseText::NEWLINE_NIX);
        if($newLinePos === false){
            $buffer = '';
        }else{
            $buffer = substr($line, $newLinePos + 1);
            $line = substr($line, 0, $newLinePos);
        }
        
        return $line;
    }

    /**
     * readByte is not available in RaiseConsoleStream
     */
    public function readByte() {
        throw new RaiseInvalidRequestException('Cannot read a single byte from a RaiseConsoleStream');
    }

    public function seek($position) {
        throw new RaiseInvalidRequestException('Cannot seek position on a RaiseConsoleStream');
    }

    public function write($str){
        echo $str;
    }

    public function writeByte($i) {
        echo chr($i);
    }

}